package com.framework.network.manager

import android.content.Context
import android.widget.Toast
import com.framework.network.factory.OkHttpClientFactory
import com.framework.network.factory.RetrofitFactory
import java.lang.ref.WeakReference

/**
 * @Description: 网络管理类
 * @Author: you
 */
class NetworkManager {
    private var networkHelp: NetworkHelp? = null

    //获取service
    var service: Any? = null

    companion object {
        private var mWeakReferenceInstance: WeakReference<NetworkManager>? = null

        @Volatile
        private var instances: NetworkManager? = null

        fun getInstance(): NetworkManager {
            return synchronized(this) {
                if (instances == null) {
                    if (mWeakReferenceInstance == null || mWeakReferenceInstance?.get() == null) {
                        mWeakReferenceInstance = WeakReference<NetworkManager>(NetworkManager())
                    }
                    instances = mWeakReferenceInstance?.get()
                }
                instances ?: NetworkManager()
            }
        }
    }

    /**
     * 获取设置各种参数的help对象
     */
    fun create(): NetworkHelp {
        if (networkHelp == null) {
            networkHelp = NetworkHelp()
        }
        return networkHelp ?: NetworkHelp()
    }

    /**
     * 初始化网络配置
     */
    fun init(context: Context) {
        if (networkHelp == null) {
            Toast.makeText(context, "请先调用build()方法", Toast.LENGTH_SHORT).show()
            return
        }
        if (networkHelp?.baseUrl.isNullOrBlank()) {
            Toast.makeText(context, "baseUrl不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        if (networkHelp?.classType == null) {
            Toast.makeText(context, "APIService接口类不能为空", Toast.LENGTH_SHORT).show()
            return
        }
        networkHelp?.run {
            val okHttpClient = OkHttpClientFactory(context).create()
            val retrofit = RetrofitFactory(okHttpClient).create(baseUrl ?: "")
            service = retrofit.create(classType)
        }
    }
}